Page({
  data: {
    userData: null,
    isLoading: false
  },

  onLoad() {
    // 加载缓存中的用户数据
    const userData = wx.getStorageSync('userData');
    if (!userData) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.navigateBack(); // 返回上一页
      return;
    }
    this.setData({ userData });
  },

  // 返回上一页
  goback() {
    wx.navigateBack();
  },

  // 选择头像
  chooseAvatar() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePath = res.tempFilePaths[0];
        // 上传头像（此处简化，直接用临时路径，实际需后端接口）
        const userData = that.data.userData;
        userData.avatar = tempFilePath;
        that.setData({ userData });
        wx.setStorageSync('userData', userData);
        wx.showToast({ title: '头像已更新', icon: 'success' });
      }
    });
  },

  // 保存个人信息
  saveProfile(e) {
    const that = this;
    const { nickname, phone, signature } = e.detail.value;

    // 验证昵称
    if (!nickname.trim()) {
      wx.showToast({ title: '请输入昵称', icon: 'none' });
      return;
    }

    that.setData({ isLoading: true });
    // 更新用户数据
    const userData = that.data.userData;
    userData.nickname = nickname.trim();
    userData.phone = phone.trim();
    userData.signature = signature.trim();

    // 保存到缓存
    wx.setStorageSync('userData', userData);
    setTimeout(() => {
      that.setData({ isLoading: false });
      wx.showToast({ title: '信息保存成功' });
      wx.navigateBack();
    }, 1000);
  }
});